package com.res.share.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.res.share.common.utils.CategoryUtils;
import com.res.share.common.Constants;
import com.res.share.mapper.ResCateGoryMapper;
import com.res.share.model.ResCategory;
import com.res.share.service.CacheService;
import com.res.share.service.ResCateGoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ResCateGoryServiceImpl extends ServiceImpl<ResCateGoryMapper, ResCategory> implements ResCateGoryService {


    @Autowired
    private CacheService cacheService;

    @Override
    public List<ResCategory> findResCategoryList(HttpServletRequest request, HttpServletResponse response) {
        List<ResCategory> resCategoryModelList = null;
        Object commonCache = cacheService.getCommonCache(Constants.CATEGORY_BASE_INFO);
        if(commonCache!=null && StringUtils.isNotEmpty(commonCache.toString())){
            resCategoryModelList=JSON.parseArray(commonCache.toString(), ResCategory.class);
        }else {
            List<ResCategory> selectList = CategoryUtils.getValue(Constants.CATE_BASE_KEY);
            resCategoryModelList = buildMenuTree(selectList, 0);

            if(!CollectionUtils.isEmpty(resCategoryModelList)){
                cacheService.setCommonCache(Constants.CATEGORY_BASE_INFO,JSON.toJSONString(resCategoryModelList));
            }
        }
        return resCategoryModelList;
    }

    @Override
    public List<ResCategory> findResCategoryListStart() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("IS_DEL", 0);
        queryWrapper.ne("ID", 0);
        queryWrapper.orderByAsc("ID");
        List<ResCategory> selectList = baseMapper.selectList(queryWrapper);
        return selectList;
    }

    private List<ResCategory> buildMenuTree(List<ResCategory> menuList, Integer pid) {
        List<ResCategory> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (Objects.equals(pid, menu.getPid())) {
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }

}
